package main

import (
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

// 定义路由规则
var routes = map[string]string{
	"/api": "http://api.example.com",
	"/web": "http://static.example.com",
	"/":    "http://www.example.com",
}

func main() {
	http.HandleFunc("/", handleRequest)

	// 启动静态文件服务
	http.Handle("/web/", http.StripPrefix("/web", http.FileServer(http.Dir("web"))))
	log.Println("Serving static files from 'static' directory")

	// 启动代理服务器
	log.Println("Starting proxy server on port 8080...")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// 获取请求路径
	path := r.URL.Path

	// 根据路径分发到不同的目标服务器
	targetURLStr, ok := routes[path]
	if !ok {
		http.NotFound(w, r)
		return
	}

	// 解析目标服务器的URL
	targetURL, err := url.Parse(targetURLStr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 创建反向代理
	proxy := httputil.NewSingleHostReverseProxy(targetURL)

	// 覆盖代理的ServeHTTP方法以修改请求头
	proxy.Director = func(req *http.Request) {
		// 调用父类的Director方法
		proxy.Director(req)

		// 添加或修改HTTP头
		req.Header.Set("X-Proxy-Handled", "true")
	}

	// 处理代理请求
	proxy.ServeHTTP(w, r)
}
